define(["../common"], function() {
	
	/**
	 * 商品列表相关
	 */
	
	// 分页
	UrlParam.setParam("page", 0);
	UrlParam.setParam("size", 20);
	UrlParam.setParam("sort", "addTime,desc");
	// 列表容器
	var $list = $(".goods-list");
	// 列表加载提示
	var $loadTip = $(".mr a");
	
	loadData();
	
	// 选择排序方式
	$("[id^=sort_]").click(function() {
		if ($list.isLocked()) {
			return false;
		}
		// 选中
		$("[id^=sort_]").removeClass("active");
		$(this).addClass("active");
		// 重新加载列表
		UrlParam.setParam("sort", $(this).id(1) + ",desc");
		UrlParam.setParam("page", 0);
		loadData(true);
	});
	
	// 加载更多
	$loadTip.click(function() {
		if (!$loadTip.isLocked()) {
			loadData();
		}
	});
	
	function loadData(isReset) {
		if (!$list.lock()) return;
		
		if (isReset) {
			$list.opacity0();
			$list.empty();
		}
		$loadTip.show().html("正在加载...");
		
		
		var loadPath = g_behaviorDomain + "/storeGoods/list/json";
		var vars = UrlParam.get();			
		var cachekey = $.param({path: loadPath, vars: vars});
		
		// 从缓存获取
		var cacheData = Common.getSessionStorage(cachekey);
		if (cacheData) {
			parseGoodsList($.parseJSON(cacheData));
			return;
		}
		
		// 从服务器获取
		
		$.ajax({
			url: loadPath + "?r=" + Math.random(),
			data: vars,
			dataType: 'text',
			success: function(data, textStatus, jqXHR) {
				Common.setSessionStorage(cachekey, data);
				parseGoodsList($.parseJSON(data));
			}
		});
		
	}
	
	function parseGoodsList(data) {
		$list.unlock(true);
		$loadTip.html("点击加载更多");
		if (data.status !== 0) {
			$loadTip.infoMsg(data.message);
			return;
		}
		var list = data.result.content;
		if (!list || list.length == 0) {
			$loadTip.html("查无记录");
			return;
		}
		$list.show();
		$list.parseHtml({
			data: list,
			beforeNode: {
				root: extStoreGoods
			}
		});
		
		GoodsList.applyLayout();
		$list.opacity1();
		
		$(window).scroll();// 加载图片
		
		UrlParam.setParam("page", data.result.number + 1);
		if (data.result.number + 1 == data.result.totalPages) {
			$loadTip.hide();
		}
	}
	
	// 动态自定义/扩展商品属性
	function extStoreGoods(sg) {// storeGoods
		// 打折
		if ((sg.promType & (1 << 0)) > 0) {
			sg.origPrice = "<del>" + sg.originalPrice + "</del>";
		} else {
			sg.origPrice = null;
		}
		// 随赠
		if ((sg.promType & (1 << 1)) > 0) {
			sg.promType = "<span>赠</span>";
		} else {
			sg.promType = null;
		}
		// 月销量
		if (!sg.dealMonth) {
			sg.dealMonth = 0;
		}
	}
	
	/**
	 * 商品类目
	 */
	(function() {
		var $rootList = $("#classifyList_root");
		var $subList = $("#classifyList_sub");
		var rootIscroll, subIscroll;
		var preventDefault = function(e) {
			e.preventDefault(); 
		}
		
		// 先缓存下模板
		$rootList.parseHtml();
		$subList.parseHtml();
		
		// 滚动分类时禁止滚动窗口
		$(".classify-select").get(0).addEventListener('touchmove', preventDefault, false);
	   	
	   	// 加载并显示根类目
		$(".sort-item-classify").click(function() {
			if (toggleRootList_().is(".panel-show")) {
				Store.visiting(function(store) {			
					loadRoot_(store.companyId);
				});
				document.addEventListener('touchmove', preventDefault, false);
				$(".navbar-fixed-bottom").addClass("fixed-bottom-hide");
			} else {
				document.removeEventListener('touchmove', preventDefault, false);
				$(".navbar-fixed-bottom").removeClass("fixed-bottom-hide");
				hideSubList_();
			}
			
		});
		
		// 点击选中的分类时重新加载数据
		$("#classifySelected").click(function() {
			$("#classifyCheckbox").addClass("check");
			// 退出选择类目
			$(".sort-item-classify").click();
			
			// 重新加载数据
			UrlParam.setParam("page", 0);
			loadData(true);
			
		});
		
		$.fn.extend({
			reHeight: function() {// 重新定义高度
				var $this = this;
				var height = $this.children().outerHeight();
				var maxHeight = $(window).scrollTop() + $(window).height() - $this.offset().top;
				if (height > maxHeight) {
					height = maxHeight;
				}
				$this.css("height", height + "px");
			}
		});
		
		$(window).on('scroll', reHeightIscroll_)
		
		function loadRoot_(companyId) {
			$rootList.empty();
			$("#classifyLoading").show();
			
			var loadPath = g_behaviorDomain + "/goodsClassify/listByCompanyId/json";
			var vars = {companyId: companyId};			
			var cachekey = $.param({path: loadPath, vars: vars});
			
			// 从缓存获取
			var cacheData = Common.getSessionStorage(cachekey);
			if (cacheData) {
				parseRoot_($.parseJSON(cacheData));
				return;
			}
			
			// 从服务器获取
			
			$.ajax({
				url: loadPath + "?r=" + Math.random(),
				data: vars,
				dataType: 'text',
				success: function(data, textStatus, jqXHR) {
					Common.setSessionStorage(cachekey, data);
					parseRoot_($.parseJSON(data));
				}
			});
		}
		
		function parseRoot_(data) {
			$("#classifyLoading").hide();
			$("#classifySelected").show();
			if (data.status !== 0) {
				$rootList.failMsg(data.message);
				return;
			}
			var list = data.result;
			if (!list || list.length == 0) {
				return;
			}
			list.unshift({
				classifyId: 0,
				name: "全部"
			});
			$rootList.parseHtml({
				data: list,
				afterNode: {
					root: registeEvent_
				}
			});
			require(["iscroll"], function() {
				rootIscroll = new IScroll('.wrapper', { mouseWheel: true,preventDefault: false });
			});
			reHeightIscroll_();			
		}
		
		function loadSub_(parentId) {
			$subList.empty();
			
			var loadPath = g_behaviorDomain + "/goodsClassify/listByParentId/json";
			var vars = {parentId: parentId};			
			var cachekey = $.param({path: loadPath, vars: vars});
			
			// 从缓存获取
			var cacheData = Common.getSessionStorage(cachekey);
			if (cacheData) {
				parseSub_($.parseJSON(cacheData));
				return;
			}
			
			// 从服务器获取
			
			var timeIndex = setTimeout(function() {
				showItemLoadIcon_(parentId);
			}, 500);
			
			$.ajax({
				url: loadPath + "?r=" + Math.random(),
				data: vars,
				dataType: 'text',
				success: function(data, textStatus, jqXHR) {
					clearTimeout(timeIndex);
					hideItemLoadIcon_(parentId);
					Common.setSessionStorage(cachekey, data);
					parseSub_($.parseJSON(data));
				}
			});
		}
		
		function parseSub_(data) {
			if (data.status !== 0) {
				$subList.failMsg(data.message);
				hideSubList_();
				return;
			}
			var list = data.result;
			if (!list || list.length == 0) {
				hideSubList_();
				return;
			}
			$subList.parseHtml({
				data: list,
				afterNode: {
					root: registeEvent_
				}
			});
			showSubList_();
			require(["iscroll"], function() {
				subIscroll = new IScroll('.sub-wrapper', { mouseWheel: true,preventDefault: false });
			});
			reHeightIscroll_();
			
		}
		
		function registeEvent_(goodsClassify) {
			var gc = goodsClassify;// goodsClassify
			
			$("#classify_" + gc.classifyId).click(function() {
				if (!gc.classifyId) {
					UrlParam.removeParam("classifyId");
					UrlParam.removeParam("deep");
				} else {
					UrlParam.setParam("classifyId", gc.classifyId);
					UrlParam.setParam("deep", gc.deep);
				}
				
				$("#classifyName").html(gc.name);
				$("#classifyCheckbox").removeClass("check");
				
				// 点击父类则加载子类,点击子类则加载新列表
				if (gc.deep === 0) {
					loadSub_(gc.classifyId);
				} else {
					$("#classifySelected").click();
				}
				
			});
			
		}
		
		function toggleRootList_() {
			return $(".classify-select .panel").toggleClass("panel-show");
		}
		
		function showSubList_() {
			return $(".popover").addClass("popover-show");
		}	
		
		function hideSubList_() {
			return $(".popover").removeClass("popover-show");
		}
		
		function showItemLoadIcon_(classifyId) {
			$("#classify_" + classifyId).children(".icon-loading").show();
		}
		
		function hideItemLoadIcon_(classifyId) {
			$("#classify_" + classifyId).children(".icon-loading").hide();
		}
		
		function reHeightIscroll_() {
			$(".wrapper").reHeight();
			if (rootIscroll) {
				rootIscroll.refresh();
			}
			if (subIscroll) {
				subIscroll.refresh();
			}
		}
	   	
	})();
});